const API_BASE = 'http://localhost:3000/api'

// 获取存储的token
function getToken() {
  return wx.getStorageSync('token') || ''
}

// 通用请求方法
const request = (url, data = {}, method = 'GET') => {
  return new Promise((resolve, reject) => {
    const token = getToken()
    const header = {
      'Content-Type': 'application/json'
    }
    
    if (token) {
      header.Authorization = `Bearer ${token}`
    }

    wx.request({
      url: API_BASE + url,
      data,
      method,
      header,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // token过期，清除本地存储并跳转登录
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          wx.showToast({
            title: '登录已过期',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }, 1500)
          reject(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (error) => {
        console.error('API请求失败:', error)
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

module.exports = {
  // 认证相关
  register(data) {
    return request('/auth/register', data, 'POST')
  },
  login(data) {
    return request('/auth/login', data, 'POST')
  },
  getUserInfo() {
    return request('/auth/me')
  },
  refreshToken() {
    return request('/auth/refresh', {}, 'POST')
  },

  // 歌曲相关
  getSongs(params = {}) {
    return request('/songs', params)
  },
  getSongDetail(id) {
    return request(`/songs/${id}`)
  },
  getSongUrl(id, quality = 1) {
    return request(`/songs/${id}/url`, { quality })
  },
  recordPlay(id, data = {}) {
    return request(`/songs/${id}/play`, data, 'POST')
  },

  // 用户相关
  getFavorites(params = {}) {
    return request('/users/favorites', params)
  },
  addFavorite(songId) {
    return request(`/users/favorites/${songId}`, {}, 'POST')
  },
  removeFavorite(songId) {
    return request(`/users/favorites/${songId}`, {}, 'DELETE')
  },
  getPlayHistory(params = {}) {
    return request('/users/history', params)
  },
  clearHistory() {
    return request('/users/history', {}, 'DELETE')
  },
  updateProfile(data) {
    return request('/users/profile', data, 'PUT')
  },
  getUserStats() {
    return request('/users/stats')
  },

  // 歌单相关
  getPlaylists(params = {}) {
    return request('/playlists', params)
  },
  getPlaylistDetail(id) {
    return request(`/playlists/${id}`)
  },
  createPlaylist(data) {
    return request('/playlists', data, 'POST')
  },
  updatePlaylist(id, data) {
    return request(`/playlists/${id}`, data, 'PUT')
  },
  deletePlaylist(id) {
    return request(`/playlists/${id}`, {}, 'DELETE')
  },
  addSongToPlaylist(playlistId, songId) {
    return request(`/playlists/${playlistId}/songs/${songId}`, {}, 'POST')
  },
  removeSongFromPlaylist(playlistId, songId) {
    return request(`/playlists/${playlistId}/songs/${songId}`, {}, 'DELETE')
  },

  // 搜索相关
  search(keyword, type = 'all', params = {}) {
    return request('/search', { keyword, type, ...params })
  },
  getSearchSuggestions(keyword) {
    return request('/search/suggest', { keyword })
  },
  getHotSearch() {
    return request('/search/hot')
  }
}